/*
 * Copyright (c) 2010-2020 IISI.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of IISI.
 */
package com.iisigroup.log.analysis;

import com.iisigroup.log.analysis.model.InfoUnit;
import com.iisigroup.log.analysis.model.StuckThreadRecord;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class Converter {
	 private final static Logger LOGGER = LoggerFactory.getLogger(Converter.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	//================================================
	//== [Enumeration types] Block Start
	//== [Enumeration types] Block End 
	//================================================
	//== [static variables] Block Start
	//== [static variables] Block Stop 
	//================================================
	//== [instance variables] Block Start
	//== [instance variables] Block Stop 
	//================================================
	//== [static Constructor] Block Start
	//== [static Constructor] Block Stop 
	//================================================
	//== [Constructors] Block Start (含init method)
	//== [Constructors] Block Stop 
	//================================================
	//== [Static Method] Block Start
	//== [Static Method] Block Stop 
	//================================================
	//== [Accessor] Block Start
	//== [Accessor] Block Stop 
	//================================================
	//== [Overrided Method] Block Start (Ex. toString/equals+hashCode)
	//== [Overrided Method] Block Stop 
	//================================================
	//== [Method] Block Start
	//####################################################################
	//## [Method] sub-block : 
	//####################################################################    
	//== [Method] Block Stop 
	//================================================
	//== [Inner Class] Block Start
	//== [Inner Class] Block Stop 
	//================================================

	/**
	 * @param unit
	 * @return
	 */
	public static StuckThreadRecord convert(InfoUnit unit) {
		final StuckThreadRecord result = new StuckThreadRecord();
		
		result.setOriginalFilePath(unit.getOriginalFilePath());
		
		final List<String> lines = unit.getOriginalData();
		for (String line : lines) {
			final String ip = extractClientIp(line);
			if (result.getClientIp() == null && StringUtils.isNotBlank(ip)) {
				result.setClientIp(ip);
			}
			final String date = extractDate(line);
			if (result.getDate() == null && StringUtils.isNotBlank(date)) {
				result.setDate(date);
			}
			final String time = extractTaiwainTime(line);
			if (result.getTime() == null && StringUtils.isNotBlank(time)) {
				result.setTime(time);				
			}
			final String userId = extractUserId(line);
			if (result.getUserId() == null && StringUtils.isNotBlank(userId)) {
				result.setUserId(userId);				
			}
		}
		final String hostIp = Converter.extractHostIp(unit.getOriginalFilePath());
		if(hostIp == null ){
			LOGGER.warn(unit.getOriginalFilePath());
		}
		result.setHostIp(hostIp);
		result.setOriginalData(unit);
		return result;
	}
	public  static String extractClientIp (final String line){
		final Matcher matcher = Pattern.compile(clientIpPattern).matcher(line);
		if(matcher.find()){
			final	String ip = matcher.group(2);
			return ip;
		}else{
			return null;
		}
	}
	public  static String extractHostIp (final String line){
		final Matcher matcher = Pattern.compile(hostIpPattern).matcher(line);
		if(matcher.find()){
			final	String ip = matcher.group(matcher.groupCount());
			return ip;
		}else{
			return null;
		}
	}
	public static String extractDate(final String line){
		final Matcher matcher = Pattern.compile(datePattern).matcher(line);
		if(matcher.find()){
			final	String answer = matcher.group(0);
			final SimpleDateFormat sdf01 = new SimpleDateFormat("yyyy/M/d",Locale.ENGLISH );
			final SimpleDateFormat sdf02 = new SimpleDateFormat("yyyyMMdd",Locale.ENGLISH );
			try {
				return sdf02.format(sdf01.parse(answer));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				// LOGGER.error("", e);
				return answer;
			}
			
		}else{
			return null;
		}
	}
	public static String extractUserId(final String line){
		final Matcher matcher = Pattern.compile(userIdPattern).matcher(line);
		if(matcher.find()){
			final	String answer = matcher.group(matcher.groupCount());
			return answer;
		}else{
			return null;
		}
	}
	public static String extractTaiwainTime(final String line){
		final Matcher matcher = Pattern.compile(taiwainTimePattern).matcher(line);
		if(matcher.find()){
			final	String answer = matcher.group(0);
			if(StringUtils.isNotBlank(answer)){
				final SimpleDateFormat sdf01 = new SimpleDateFormat("ah時m分s秒",Locale.TAIWAN );
				final SimpleDateFormat sdf02 = new SimpleDateFormat("HHmmss",Locale.ENGLISH );
				try {
					String data = sdf02.format(sdf01.parse(answer));
					return data;
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					// LOGGER.error("", e);
					return answer;
				}
			}
			return answer;
		}else{
			return null;
		}
	}
	private static final String datePattern = "\\d{4}\\/\\d{1,}\\/\\d{1,}";
	private static final String clientIpPattern ="(Proxy-Client-IP):.*(\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b)"; 
	private static final String hostIpPattern ="(\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b)"; 
	private static final String userIdPattern ="userId:.*(.\\w.\\w\\d{6})"; 
	
	private static final String taiwainTimePattern = "(\\S午\\d{1,}時\\d{1,}分\\d{1,}秒)";
}
